package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.auth.constants.JwtConstants.DOMAIN;

/**
 * @author 虎哥
 */
@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        try {
            // 1.根据用户名和密码查询用户
            UserDTO user = userClient.queryUserByUsernameAndPassword(username, password);
            // 2.判断查询结果
            if(user == null){
                // 查询失败
                throw new LyException(400, "用户名或密码错误");
            }
            // 3.如果正确，生成JWT
            String jwt = jwtUtils.createJwt(UserDetails.of(user.getId(), user.getUsername()));
            // 4.写入用户cookie
            writeCookie(response, jwt);
        } catch (FeignException e) {
            throw new LyException(e.status(), e.getMessage());
        }
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        // 1.获取cookie中的jwt
        String jwt = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
        if (StringUtils.isBlank(jwt)) {
            // 用户未登录，无需处理
            return;
        }
        try {
            // 2.解析并获取用户id
            Payload payload = jwtUtils.parseJwt(jwt);
            Long userId = payload.getUserDetail().getId();
            // 3.删除redis中的jti
           jwtUtils.clearJwt(userId);
        } catch (Exception e) {
            // 用户未登录，无需清理redis
        }
        // 4.删除cookie
        CookieUtils.deleteCookie(JwtConstants.COOKIE_NAME, DOMAIN, response);
    }

    private void writeCookie(HttpServletResponse response, String jwt) {
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, jwt);
        cookie.setDomain(DOMAIN);
        cookie.setHttpOnly(true);
        cookie.setMaxAge(-1);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
